var up_doc = window.dialogArguments.document;

function $(name) {
	return document.getElementsByName(name);
}

function $2(name) {
	return window.dialogArguments.document.getElementsByName(name);
}

var inputMap = {
	"my:原供应商名称" : "oldSupplierName",
	"my:原供应商编码" : "oldSupplierCode",
	"my:备注" : "remark",
	"my:目标供应商名称" : "newSupplierName",
	"my:目标供应商编码" : "newSupplierCode"
};

var notAllowBlank = {
	oldSupplierName : "原供应商名称",
	oldSupplierCode : "原供应商编码",
	newSupplierName : "目标供应商名称"
}

function corpValueChange(node) {
	var selectNodes = $('corpSelect');
	for (var i = 0; i < selectNodes.length; i++) {
		selectNodes[i].value = node.value;
	}
	var inputs = document.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].id != 'ok_button')
			inputs[i].value = "";
	}
}

/**
 * 全角转半角，小写转大写
 * 
 * @param {}
 *            field
 */
function replaceIllegalCharacter(field) {
	var charlist = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	charlist += "abcdefghijklmnopqrstuvwxyz";
	charlist += "0123456789";
	charlist += " `~!@#$%^&*()_+-={}|[]\:\\\";'<>?,./";// 半角空格

	var providerName = field.value;
	var result = "";
	for (var i = 0; i < providerName.length; i++) {
		var c1 = providerName.charAt(i);
		var c2 = providerName.charCodeAt(i);
		if ("　" == c1) {
			result += " ";
		} else if ("，" == c1) {
			result += ",";
		} else if ("。" == c1) {
			result += ".";
		} else {
			if (charlist.indexOf(String.fromCharCode(c2 - 65248)) > -1) {
				result += String.fromCharCode(c2 - 65248);
			} else {
				result += c1;
			}
		}
	}
	field.value = result.toUpperCase();
}

/**
 * 更名或合并切换
 * 
 * @param {}
 *            node
 */
function operateValueChange(node) {
	var inputs = getParentTR(node).parentNode.getElementsByTagName("input");
	if (node.value == 0) {
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].name == "newSupplierCode") {
				inputs[i].readOnly = true;
				inputs[i].className = "readonly";
				inputs[i].value = "";
			} else if (inputs[i].name == "newSupplierName") {
				inputs[i].readOnly = false;
				inputs[i].className = "fill";
				inputs[i].value = "";
			}
		}
	} else {
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].name == "newSupplierCode") {
				inputs[i].readOnly = false;
				inputs[i].className = "fill";
				inputs[i].value = "";
			} else if (inputs[i].name == "newSupplierName") {
				inputs[i].readOnly = true;
				inputs[i].className = "readonly";
				inputs[i].value = "";
			}
		}
	}
}

function supplierCodeValueChange(field, supplierName) {
	setButtonDisabled(true);
	replaceIllegalCharacter(field);

	if ($2("my:审批状态")[0] && $2("my:审批状态")[0].value == "code") {
		field.value = field.value.replace(/ /g, "");
		setButtonDisabled(false);
	} else {
		var supplierCode = field.value;
		if (supplierCode.replace(/ /g, "") == "") {
			var inputs = getParentTR(field).parentNode
					.getElementsByTagName("input");
			for (var i = 0; i < inputs.length; i++) {
				if (inputs[i].name == supplierName) {
					inputs[i].value = "";
					break;
				}
			}
			setButtonDisabled(false);
		} else {
			var pk_corp = $("corpSelect")[0].value.replace("key_", "");
			_ajax(
					"../../oa2uapController.do?method=financeProviderOperate&operate=1&code="
							+ supplierCode + "&pk_corp=" + pk_corp + "&isNew="
							+ (field.name == "newSupplierCode"),
					function(data) {
						var inputs = getParentTR(field).parentNode
								.getElementsByTagName("input");
						for (var i = 0; i < inputs.length; i++) {
							if (inputs[i].name == supplierName) {
								inputs[i].value = data.result;
								break;
							}
						}
					});
		}
	}
}
/**
 * 输入原供应商编码，查询原供应商名称
 * 
 * @param {}
 *            field
 */
function oldSupplierCodeValueChange(field) {
	supplierCodeValueChange(field, "oldSupplierName");
}

/**
 * 输入目标供应商编码，目标原供应商名称
 * 
 * @param {}
 *            field
 */
function newSupplierCodeValueChange(field) {
	supplierCodeValueChange(field, "newSupplierName");
}

function setButtonDisabled(disabled) {
	document.getElementById("ok_button").disabled = disabled;
}

function setFieldReadOnly(field) {
	if (field.tagName.toUpperCase() == "SELECT") {
		field.disabled = true;
	} else {
		field.readOnly = true;
		field.className = 'readonly';
	}
}

function getCheckArray(fieldName) {
	var checkArray = [];
	for (var i = 0; i < $("operate").length; i++) {
		if ($("operate")[i].value == 0) {
			checkArray.push($(fieldName)[i].value);
		}
	}
	return checkArray;
}

function writeToForm(isNewForm) {
	if (isNewForm) {
		var supplierNames = $2("my:原供应商名称");
		var supplierNameNodes = $("oldSupplierName");
		var oldLength = supplierNames.length;

		var upTR = getParentTR(supplierNames[supplierNames.length - 1]);
		for (var i = 0; i < supplierNameNodes.length; i++) {
			upTR.id = "oper";
			window.dialogArguments.addEmpty();
		}

		for (var i = 0; i < oldLength; i++) {
			getParentTR($2("my:原供应商名称")[0]).id = "oper";
			window.dialogArguments.del();
		}
		for (var i = 0; i < supplierNameNodes.length; i++) {
			$2("my:pk_corp")[i].value = $('corpSelect')[i].value;
			$2("my:制造部")[i].value = $("corpSelect")[i].options[$("corpSelect")[i].options.selectedIndex].text;
			$2("my:更名或合并")[i].value = $('operate')[i].value == 0 ? "更名" : "合并";
			for (var key in inputMap) {
				$2(key)[i].value = $(inputMap[key])[i].value;
			}
			$2("my:供货类别")[i].value = "无";
		}
		window.close();
	} else {
		$2("my:_目标供应商编码")[0].value = "1";
		var operateNodes = $("operate");
		for (var i = 0; i < operateNodes.length; i++) {
			if (operateNodes[i].value == 0) {
				$2("my:目标供应商编码")[i].value = $("newSupplierCode")[i].value;
			}
		}
		window.close();
	}
}

/**
 * 将填写的内容写入到表单
 */
function okButtonClick() {
	setButtonDisabled(true);
	if ($2("my:审批状态")[0] && $2("my:审批状态")[0].value == "code") {
		/**
		 * 集团采购部提供编码
		 */
		var newSupplierCodeNodes = $("newSupplierCode");
		var oldSupplierCodeNodes = $("oldSupplierCode");
		var operateNodes = $("operate");
		var newCodes = [];
		for (var i = 0; i < newSupplierCodeNodes.length; i++) {
			if (newSupplierCodeNodes[i].value.replace(/ /g, "") == "") {
				alert("目标供应商编码不能为空。");
				return setButtonDisabled(false);
			}
			if (operateNodes[i].value == 0) {
				if (newSupplierCodeNodes[i].value != oldSupplierCodeNodes[i].value) {
					newCodes.push(newSupplierCodeNodes[i].value);
				}
			}

			for (var j = 0; j < newSupplierCodeNodes.length; j++) {
				if (i != j) {
					if (newSupplierCodeNodes[i].value == newSupplierCodeNodes[j].value) {
						alert("目标供应商编码" + newSupplierCodeNodes[i].value + "重复");
						return setButtonDisabled(false);
					}
					if (oldSupplierCodeNodes[i].value == oldSupplierCodeNodes[j].value) {
						alert("原供应商编码" + oldSupplierCodeNodes[i].value + "重复");
						return setButtonDisabled(false);
					}
					if (oldSupplierCodeNodes[i].value == newSupplierCodeNodes[j].value) {
						alert("供应商编码" + oldSupplierCodeNodes[i].value + "重复");
						return setButtonDisabled(false);
					}
				}
			}
		}

		if (newCodes.length != 0) {
			_ajax(
					'../../oa2uapController.do?method=financeProviderOperate&operate=3&name='
							+ newCodes.join(","), function() {
						writeToForm(false);
					});
		} else {
			writeToForm(false);
		}

	} else {
		var supplierNameNodes = $("newSupplierName");
		for (var i = 0; i < supplierNameNodes.length; i++) {
			for (var key in notAllowBlank) {
				if ($(key)[i].value == "") {
					alert(notAllowBlank[key] + "不能为空");
					return setButtonDisabled(false);
				} else if ($("newSupplierName")[i].value == $("oldSupplierName")[i].value) {
					alert("原供应商名称和目标供应商名称不能一样");
					return setButtonDisabled(false);
				} else {
					for (var j = 0; j < supplierNameNodes.length; j++) {
						if (i != j
								&& $("newSupplierName")[i].value == $("newSupplierName")[j].value) {
							alert("存在多行相同的目标供应商");
							return setButtonDisabled(false);
						}
						if (i != j
								&& $("oldSupplierName")[i].value == $("oldSupplierName")[j].value) {
							alert("存在多行相同的原供应商");
							return setButtonDisabled(false);
						}
					}
				}
			}
		}
		var newSupplierNameArray = getCheckArray("newSupplierName");
		if (newSupplierNameArray.length > 0) {
			_ajax(
					'../../oa2uapController.do?method=financeProviderOperate&operate=2&name='
							+ encodeURIComponent(newSupplierNameArray
									.join('【连接符】')), function() {
						writeToForm(true);
					});
		} else {
			writeToForm(true);
		}
	}
}

function _ajax(url, operator) {
	window.parent.document.getElementById("lodingDiv").style.height = window.parent.document.body.clientHeight
			- 3 + "px";
	window.parent.document.getElementById("lodingDiv").style.display = '';
	var xmlhttp = null;
	if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,
		xmlhttp = new XMLHttpRequest();
	} else {// code for IE6, IE5
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				text = xmlhttp.responseText;
				if (text == 1) {
					alert("原供应商编码不能为空");
				} else if (text == 2) {
					alert("用户还未登陆，或者已掉线");
				} else if (text == 3) {
					alert("制造部ID不能为空。");
				} else if (text == 4) {
					alert("常数不能为空");
				} else if (text == 4) {
					alert("目标供应商名称不能为空");
				} else {
					var data = eval("(" + text + ")");
					if (data.success)
						operator(data);
					else
						alert(data.result);
				}
			} else {
				alert("连接服务器异常");
			}
			window.parent.document.getElementById("lodingDiv").style.display = 'none';
			setButtonDisabled(false);
		}
	};
	xmlhttp.open("get", url + "&temp=" + Math.random(), true);
	xmlhttp.send();
}

window.onload = function() {

	/**
	 * 界面初始化
	 */
	if ($2("my:审批状态")[0] && $2("my:审批状态")[0].value == "code") {
		/**
		 * 集团采购部提供编码
		 */
		var firstTR = getParentTR(document.getElementById("repeatTable").childNodes[0].childNodes[0].childNodes[0]);
		var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
		repeatOperator.addListeners(firstTR);
		repeatOperator.setAllowAdd(false);
		repeatOperator.setAllowDel(false);

		$('corpSelect')[0].options.add(new Option($2("my:制造部")[0].value,
				$2("my:pk_corp")[0].value));
		$('corpSelect')[0].options.selectedIndex = 0;

		var supplierNames = $2("my:原供应商名称");
		repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
		for (var i = 0; i < supplierNames.length; i++) {
			if ($2("my:pk_corp")[0].value != "") {
				$('corpSelect')[i].value = $2("my:pk_corp")[0].value;
			}
			setFieldReadOnly($('corpSelect')[i]);
			if ($2("my:更名或合并")[0].value != "") {
				$('operate')[i].value = $2("my:更名或合并")[i].value == "更名" ? 0 : 1;
				operateValueChange($('operate')[i]);
			}
			setFieldReadOnly($('operate')[i]);
			for (var key in inputMap) {
				$(inputMap[key])[i].value = $2(key)[i].value;
				setFieldReadOnly($(inputMap[key])[i]);
			}
			if ($("operate")[i].value == 0) {
				$("newSupplierCode")[i].readOnly = false;
				$("newSupplierCode")[i].className = "fill";
			}
		}

	} else {
		/**
		 * 填写新建表单
		 */
		// 重复表初始化
		var firstTR = getParentTR(document.getElementById("repeatTable").childNodes[0].childNodes[0].childNodes[0]);
		var repeatOperator = new RepeateTableOperator(firstTR.parentNode);
		repeatOperator.addListeners(firstTR);
		// 新增行，制造部下拉列表的值同第一行
		repeatOperator.setAfterAddTrOperate(function() {
					for (var i = 1; i < $('corpSelect').length; i++) {
						$('corpSelect')[i].value = $('corpSelect')[0].value;
						if ($("newSupplierName")[i].value == ""
								&& $("newSupplierCode")[i].value == ""
								&& $("oldSupplierCode")[i].value == "") {
							operateValueChange($("operate")[i]);
						}
					}
				});

		// 制造部下拉列表选择项设置
		var oaAccountID = up_doc.getElementById('my:单位选择器')['default'];

		for (var key in corpMap) {
			if (corpMap[key] && corpMap[key] == oaAccountID) {
				$('corpSelect')[0].options
						.add(new Option(corpMap1[key][1], key));

				if (oaAccountID == "5686590792835548528") {
					$('corpSelect')[0].options.add(new Option("福州福耀模具科技有限公",
							"key_1215"));
				}

				break;
			}
		}
		$('corpSelect')[0].options.selectedIndex = 0;

		if (oaAccountID == "5686590792835548528") {
			if ($2("my:pk_corp")[0].value != "") {
				$('corpSelect')[0].value = $2("my:pk_corp")[0].value;
			}
		}

		// 把表单的内容复制到填写界面的对应的输入框
		var supplierNames = $2("my:更名或合并");
		repeatOperator.addEmptyTR(firstTR, supplierNames.length - 1);
		for (var i = 0; i < supplierNames.length; i++) {
			if ($2("my:pk_corp")[0].value != "") {
				$('corpSelect')[i].value = $2("my:pk_corp")[0].value;
			}
			if ($2("my:更名或合并")[0].value != "") {
				$('operate')[i].value = $2("my:更名或合并")[i].value == "更名" ? 0 : 1;
				operateValueChange($('operate')[i]);
			}
			for (var key in inputMap) {
				$(inputMap[key])[i].value = $2(key)[i].value;
			}
		}
	}
};
